package cn.bytecollege.filter;

import cn.bytecollege.constant.Resource;
import cn.bytecollege.entity.Admin;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 让没有登录时，先登录才能访问其他页面
 * @author qy
 */
@WebFilter(filterName = "LoginValidFilter",value = "/*")
public class LoginValidFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpSession session = req.getSession();

        //获取请求的地址
        String uri = req.getRequestURI();
        //获取请求方法
        String method = req.getMethod();
        //解决post请求中文数据乱码问题
        if(method.equalsIgnoreCase("post")){
            request.setCharacterEncoding("utf-8");
        }
        //请求登录页面直接放行
        if (uri.contains("login.jsp") || uri.contains("/admin/login")){
            chain.doFilter(request,response);
            return;
        }

        Admin admin = (Admin) session.getAttribute("admin");
        if (admin == null){
            //第一次登录没有携带session，需要先放行css和js
            String s = req.getRequestURL().toString();
            if (s.contains("css")||s.contains("js")||s.contains("img")) {
                response.setContentType("text/html;charset=utf-8");
                chain.doFilter(request,response);
                return;
            }
            //没有登录，转回登录页
            request.getRequestDispatcher(Resource.PAGE_LOCATION+"/adminLogin.jsp").forward(request,response);
            return;
        }
        chain.doFilter(request, response);
    }
}
